var app = angular.module('meetingApp.directives');

app.directive('uploadOss' , ['layerService', 'toastPCService',function(layer , toast){
    return {
        restrict : 'A',
        scope : {
            ngModel : '=',
            uploadIng : '=',
        },
        //attr需要id
        link : function(scope , element , attr){

            var accessid = '',
            accesskey = '',
            host = '',
            policyBase64 = '',
            signature = '',
            callbackbody = '',
            key = '',
            expire = 0,
            g_object_name = '',
            accept = attr.accept;
            console.log(accept)
            now = timestamp = Date.parse(new Date()) / 1000; 

            function send_request(){
                var xmlhttp = null;
                if (window.XMLHttpRequest){
                    xmlhttp=new XMLHttpRequest();
                }else if (window.ActiveXObject){
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                if (xmlhttp!=null){
                    serverUrl = window._host+'/common/oss_setting/getSetting'
                    xmlhttp.open( "GET", serverUrl, false );
                    xmlhttp.send( null );
                    return JSON.parse(xmlhttp.responseText);
                }else{
                    toast.show(2 , '你的浏览器不支持上传');
                }
            };

            function get_signature(){
                // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
                now = timestamp = Date.parse(new Date()) / 1000; 
                if (expire < now + 3){
                    var data = send_request();
                    data = data['data'];
                    host = data['host']
                    policyBase64 = data['policy']
                    accessid = data['accessid']
                    signature = data['signature']
                    expire = parseInt(data['expire'])
                    callbackbody = data['callback'] 
                    key = data['dir']
                    return true;
                }
                return false;
            };

            function get_suffix(filename) {
                pos = filename.lastIndexOf('.')
                suffix = ''
                if (pos != -1) {
                    suffix = filename.substring(pos)
                }
                return suffix;
            }
            
            function calculate_object_name(filename){
                suffix = get_suffix(filename)
                g_object_name = key + (new Date().getTime())+'_'+parseInt(Math.random()*100+1) + suffix
            }
            
            function set_upload_param(up, filename, ret){
                if (ret == false) {
                    ret = get_signature()
                }
                // g_object_name = key;
                calculate_object_name(filename);

                new_multipart_params = {
                    'key' : g_object_name,
                    'policy': policyBase64,
                    'OSSAccessKeyId': accessid, 
                    'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
                    'callback' : callbackbody,
                    'signature': signature,
                };

                up.setOption({
                    'url': host,
                    'multipart_params': new_multipart_params
                });
                up.start();
            }

            var fileType = { //只允许上传图片和zip文件
                image : { title : "Image files", extensions : "jpg,gif,png,bmp" }, 
                doc : { title : "Doc files", extensions : "txt,doc,docx" },
                video : { title : 'VIdeo files' , extensions : "mp4,avi,m4v"}
            };

            var types = [];
            accept.split('|').forEach(item => {
                types.push(fileType[item]);
            })


            var uploader = new plupload.Uploader({
                runtimes : 'html5,flash,silverlight,html4',
                browse_button : attr.id, 
                //multi_selection: false,
                // container: document.getElementById('container'),
                flash_swf_url : window._host+'/static/public/js/plupload-2.1.2/js/Moxie.swf',
                silverlight_xap_url : window._host+'/static/public/js/plupload-2.1.2/js/Moxie.xap',
                url : 'http://oss.aliyuncs.com',

                filters: {
                    // mime_types : [ //只允许上传图片和zip文件
                    // { title : "Image files", extensions : "jpg,gif,png,bmp" }, 
                    // { title : "Doc files", extensions : "txt,doc,docx" },
                    // { title : 'VIdeo files' , extensions : "mp4,avi"}
                    // ],
                    mime_types : types,
                    max_file_size : '2000mb', //最大只能上传10mb的文件
                    prevent_duplicates : true //不允许选取重复文件
                },

                init: {
                    PostInit: function() {
                        console.log('init')
                    },
                    FilesAdded: function(up, files) {
                        plupload.each(files, function(file) {
                            var innerHTML = '<div class="progress_box" id="' + file.id + '"><b></b>'
                            +'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                            +'</div>';
                            element.find('.progress_box').remove();
                            element.parents('.row_progress_box').after(innerHTML)
                            set_upload_param(uploader, files['0'].name, false);
                        });
                    },

                    BeforeUpload: function(up, file) {
                        console.log(file)
                        //set_upload_param(up, file.name, true);
                    },

                    //实时显示上传进度
                    UploadProgress: function(up, file) {
                        scope.$apply(function(){
                            scope.uploadIng = 1;
                        })
                        var d = document.getElementById(file.id);
                        d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                        var prog = d.getElementsByTagName('div')[0];
                        var progBar = prog.getElementsByTagName('div')[0]
                        progBar.style.width= 2*file.percent+'px';
                        progBar.setAttribute('aria-valuenow', file.percent);
                    },

                    FileUploaded: function(up, file, info) {
                        if (info.status == 200){
                            var d = document.getElementById(file.id);
                            var prog = d.getElementsByTagName('div')[0];
                            var progBar = prog.getElementsByTagName('div')[0]
                            progBar.style.width= 100+'%';
                            console.log(info)
                            scope.$apply(function(){
                                scope.uploadIng = 0;
                                scope.ngModel = host+'/'+g_object_name;
                            })
                        }
                        else{
                            toast.show(2 , '文件上传失败');
                        }
                    },

                    Error: function(up, err) {
                        if (err.code == -600) {
                            toast.show(2 , '选择的文件太大了');
                        }
                        else if (err.code == -601) {
                            toast.show(2 , '选择的文件后缀不对');
                        }
                        else if (err.code == -602) {
                            toast.show(2 , '这个文件已经上传过一遍了');
                        }
                        else{
                            toast.show(2 , err.response);
                        }
                    }
                }
            });
            uploader.init();

        }
    }
}])